// static/user/js/modules/equipment-list.js
class EquipmentList {
    constructor() {
        this.container = document.querySelector('.equipment-list__container');
        this.loadingElement = document.querySelector('.equipment-list__loading');
        this.currentCategoryId = '';
        this.searchKeyword = '';
        this.init();
    }

    async init() {
        this.bindGlobalEvents();
        this.bindEvents();
        this.loadItems();
    }
    bindEvents() {

        // 卡片点击事件
        this.container.addEventListener('click', async (e) => {
            const card = e.target.closest('.equipment-card');
            if (card) {
                const itemId = card.dataset.itemId;
                console.log('点击了设备卡片', itemId);
                EquipmentDetails.show(itemId);
            }
        });
    }

    bindGlobalEvents() {
        // 头部搜索
        const searchInput = document.getElementById('searchInput');
        const searchBtn = document.querySelector('.search-btn');

        // 输入防抖
        let searchTimer;
        searchInput.addEventListener('input', (e) => {
            clearTimeout(searchTimer);
            searchTimer = setTimeout(() => {
                this.searchKeyword = e.target.value.trim();
                this.loadItems();
            }, 500);
        });

        searchBtn.addEventListener('click', () => {
            this.searchKeyword = searchInput.value.trim();
            this.loadItems();
        });

        window.addEventListener('categoryChanged', (e) => {
            this.currentCategoryId = e.detail.categoryId;
            this.loadItems();
        });
    }


    async loadItems() {
        this.showLoading();
        try {
            const params = {
                categoryId: this.currentCategoryId,
                itemName: this.searchKeyword
            };
            const items = await fetchData(API.ITEM.LIST, params);
            this.render(items);
        } catch (error) {
            Alert.show('数据加载失败: ' + error.message, 'error');
        } finally {
            this.hideLoading();
        }
    }

    // equipment-list.js 修改render方法
    render(items) {
        this.container.innerHTML = items.map(item => `
    <div class="equipment-card" data-item-id="${item.id}">
      ${this.getStatusBadge(item)}
      <img class="equipment-card__image" 
           src="${item.imgUrl || '/static/default-image.jpg'}" 
           alt="${item.name}"
           loading="lazy">
      <div class="equipment-card__content">
        <h3 class="equipment-card__title">${item.name}</h3>
        <p class="equipment-card__specs">${item.specs}</p>
        
        <div class="equipment-card__meta">
          <div class="meta-item">
            <i class="icon-rent"></i>
            <span>¥${item.dailyRate}/天</span>
          </div>
          <div class="meta-item">
            <i class="icon-deposit"></i>
            <span>押金¥${item.deposit}</span>
          </div>
        </div>

        <div class="equipment-card__stock">
          <span class="stock-badge ${item.availableStock > 0 ? 'stock-available' : 'stock-out'}">
            ${item.availableStock > 0 ?
            `可租${item.availableStock}件` :
            '已租罄'}
          </span>
          <span class="total-stock">总库存 ${item.totalStock}件</span>
        </div>
      </div>
      <button class="add-to-cart-btn" 
              data-product-id="${item.id}"
              onclick="event.stopPropagation(); Cart.addItem('${item.id}')">
        <i class="icon-add"></i> 加入租购单
      </button>
    </div>
  `).join('');
    }

    getStatusBadge(item) {
        if (item.maintenanceStatus === 1) {
            return '<div class="maintenance-badge">维护中</div>';
        }
        return '';
    }


    showLoading() {
        this.loadingElement.style.display = 'block';
    }

    hideLoading() {
        this.loadingElement.style.display = 'none';
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    new EquipmentList();
});